package com.cos.emp.web.controller;

import com.cos.emp.common.Const;
import com.cos.emp.entity.Emp;
import com.cos.emp.services.EmpServices;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @author: COS
 * @time: 2021/11/18 15:00
 * @description:
 */
@Controller
@RequestMapping("/emp")
public class EmpController {
    @Autowired
    private EmpServices es;

    @RequestMapping("/updateEmp")
    public String updateEmp(Emp emp) {
        es.updateEmp(emp);
        return "redirect:/emp/index";
    }

    @RequestMapping("/getEmpByEno")
    public String getEmpByEno(Integer eno, Model model) {
        Emp e = es.getEmpByEno(eno);
        model.addAttribute("emp", e);
        return "updateEmp";
    }

    @RequestMapping("/addEmp")
    public String addEmp(Emp emp) {
        System.out.println("--" + emp.getEsex() + "--");
        es.addEmp(emp);
        return "redirect:/emp/index";
    }


    @RequestMapping("/delEmp")
    public String delEmp(@RequestParam(value = "eno", required = false) Integer eno) {
        if (eno != null) {
            es.delEmp(eno);
        }
        //重定向
        return "redirect:/emp/index";
    }


    /**
     * @author: COS
     * @return:
     * @time: 2021/11/18 16:44
     * @description:
     * @RequestParam(defaultValue = "1") 当他修饰的值为null的时候给默认值1
     */
    @RequestMapping("/index")
    public String getAll(Model model, @RequestParam(defaultValue = "1") Integer pageIndex) {
        PageInfo<Emp> empByPage = es.getEmpByPage(pageIndex);
        model.addAttribute("empInfo", empByPage);
        return "index";
    }

    @RequestMapping("/login")
    @ResponseBody
    public String login(String ename, String pwd, HttpSession session) {
        Emp e = es.login(ename, pwd);
        if (e != null) {
            //保存用户登录数据到session
            session.setAttribute(Const.IS_LOGIN, e);
            //清除之前的手机验证码
            session.removeAttribute(Const.PHONE_CODE);
            //返回成功信息
            return Const.SUCCESS;
        }
        return Const.FAILE;
    }

}
